package com.zwk.edu.controller;


import com.zwk.base.entity.CommonResult;
import com.zwk.edu.client.VodClient;
import com.zwk.edu.entity.Video;
import com.zwk.edu.service.VideoService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author zwk
 * @since 2022-08-22
 */
@RestController
@RequestMapping("/edu/video")
@CrossOrigin
public class VideoController {

    @Qualifier("com.zwk.edu.client.VodClient")
    @Autowired
    private VodClient vodClient;

    @Autowired
    private VideoService videoService;

    // 添加小节
    @PostMapping("/addVideo")
    public CommonResult addVideo(@RequestBody Video video){

        boolean result = videoService.save(video);
        if (result){
            return CommonResult.ok();
        }
        return CommonResult.error();
    }

    // 删除小节
    @DeleteMapping("{id}")
    public CommonResult deleteById(@PathVariable("id") String id){

        // 根据小节id获取视频id;
        Video video = videoService.getById(id);
        String videoSourceId = video.getVideoSourceId();

        boolean result = videoService.removeById(id);
        if (result){
            // 删除视频, 判断视频id是否为空
            if (ObjectUtils.isNotEmpty(videoSourceId)){
                CommonResult commonResult = vodClient.removeAliyunVideo(video.getVideoSourceId());
                // 触发熔断
                if (!commonResult.getSuccess()){
                    return CommonResult.error();
                }
            }
            return CommonResult.ok();
        }
        return CommonResult.error();
    }

    // 根据id查询小节
    @GetMapping("/getVideo/{id}")
    public CommonResult getVideo(@PathVariable("id") String id){

        Video video = videoService.getById(id);

        return CommonResult.ok().data("video", video);
    }

    // 修改小节
    @PostMapping("/updateVideo")
    public CommonResult updateVideo(@RequestBody Video video){

        boolean result = videoService.updateById(video);

        if (result){
            return CommonResult.ok();
        }
        return CommonResult.error();
    }

}

